package com.huan;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test4_ReaderWriter {
    public static void main(String[] args) throws IOException {
        final int port = 10000;
        ServerSocket socket = null;
        for (int i=10000;i<65535;i++){
            try {
                socket = new ServerSocket(i);
                break;
            }catch (Exception e){
                e.printStackTrace();
                if (e instanceof BindException){
                    System.out.println("端口"+i+"已被占用");
                }
            }
            System.out.println(socket.getInetAddress().getHostName()+"启动了，监听端口："+socket.getLocalPort());

            DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            Date date = null;
            String time = null;
            while (true){
                //获取一个与客户端的套接字
                Socket s = socket.accept();
                System.out.println("获取了一个与客户端："+s.getRemoteSocketAddress()+"的连接");
                date = new Date();
                time = dateFormat.format(date);

                //套接字编程的底层解释io
                //转换流，将字节流转换为字符流
                try (
                        OutputStreamWriter outputStreamWriter =
                                new OutputStreamWriter(s.getOutputStream())){
                        outputStreamWriter.write(time);
                        outputStreamWriter.flush();
                }catch (Exception e){
                    e.printStackTrace();
                }
                socket.close();
                System.out.println("服务器断开与客户的连接");
            }
        }
    }
}
